<template>
	<view>
		<view class="loginContent">
			<view class="loginTop">
				<view class="loginLog">
					<image class="img" src="../../static/login/log.png" mode="widthFix"></image>
				</view>
			</view>
			<view class="loginMain">
				<uni-section title="物流管控平台" type="line" titleColor="#FFF">
					<uni-forms>
						<uni-easyinput
							prefixIcon="person"
							:trim="true"
							:inputBorder="true"
							v-model="userName"
							placeholderStyle="color:#00aded;"
							placeholder="请输入用户名(手机号或车牌号)"
						></uni-easyinput>
						<uni-easyinput
							prefixIcon="locked"
							:inputBorder="true"
							:trim="true"
							type="password"
							v-model="password"
							placeholderStyle="color:#00aded;"
							placeholder="请输入密码"
						></uni-easyinput>
					</uni-forms>
					<view class="forgetPwd" @click="forgetPwd">忘记密码?</view>
				</uni-section>
			</view>
			<view class="loginBtn">
				<button class="btn" @click="onclick" :loading="loading">登 录</button>
			</view>
			<!-- <view class="loginBtn">
				<button class="btn" @click="register" :loading="loading">注 册</button>
			</view> -->
			<view class="loginFloot" v-if="version != null">
				<text>当前版本号:</text>
				<text>{{ version }}</text>
			</view>
			<view class="updateBtn" v-if="version != null">
				<view @click="getupdate" :loading="loading">如有需要请点击此处下载更新</view>
			</view>
		</view>

		<view class="driverPop">
			<uni-popup ref="popup" type="dialog">
				<view class="popContent" style="background-color: white; border-radius: 1%">
					<view class="main" style="margin: 10px">
						<dil-Form ref="form_rgt" :formId="470" v-model="form_rgt" labelPosition="left" labelWidth="90px" v-if="formShow"></dil-Form>
					</view>
					<view class="footer" style="display: flex; margin-bottom: 40rpx">
						<button type="default" @click="canceAdd">取消</button>
						<button type="primary" @click="confirmAdd">确认</button>
					</view>
				</view>
			</uni-popup>
		</view>
	</view>
</template>

<script>
import { sha1 } from '../../utils/sha1.js';
export default {
	data() {
		return {
			form: {},
			form_rgt: {},
			formShow: false,
			loading: false,
			userName: '',
			password: '',
			passwordSha1: '',
			version: null
		};
	},
	created() {
		// #ifdef APP-PLUS
		//TpvwClq7
		this.version = plus.runtime.version;
		// this.getVersion();
		// // #endif
		this.getUserName();
	},
	methods: {
		getUserName() {
			if (uni.getStorageSync('userName') && uni.getStorageSync('passWord')) {
				this.userName = uni.getStorageSync('userName');
				this.password = uni.getStorageSync('passWord');
			}
		},
		forgetPwd() {
			uni.showToast({
				title: '请联系业务负责人!',
				icon: 'error',
				duration: 2000
			});
		},
		sendMessage() {
			uni.switchTab({
				url: '/pages/index/index'
			});
		},
		async getDytys(userInfo) {
			const res = await this.$mySsoRequest({
				url: '/icore.icp.web/pass/v1/sysorgs/findOrgs?companyId=' + userInfo.companyId,
				method: 'GET'
			});
			let _this = this;
			if (res.data.code === '0') {
				let tempData = res.data.data;
				if (tempData.length > 0) {
					let orgId = uni.getStorageSync('orgId') ? JSON.parse(uni.getStorageSync('orgId') || 'null') || '' : '';
					let orgName = '';
					let orgCode = '';
					let dutyName = '';
					let dutyId = '';
					let depTypeCode = '';
					if (orgId && orgId !== '' && orgId !== null) {
						let obj = tempData.find((x) => x.orgId === orgId);
						if (obj) {
							orgId = orgId;
							orgName = obj.orgName;
							orgCode = obj.orgCode;
							depTypeCode = obj.depType;
							dutyName = obj.dutys ? obj.dutys[0].dutyName : '';
							dutyId = obj.dutys ? obj.dutys[0].dutyId : '';
						} else {
							orgName = tempData[0].orgName;
							orgId = tempData[0].orgId;
							orgCode = tempData[0].orgCode;
							depTypeCode = tempData[0].depType;
							dutyName = tempData[0].dutys ? tempData[0].dutys[0].dutyName : '';
							dutyId = tempData[0].dutys[0] ? tempData[0].dutys[0].dutyId : '';
						}
					} else {
						orgName = tempData[0].orgName;
						orgId = tempData[0].orgId;
						orgCode = tempData[0].orgCode;
						depTypeCode = tempData[0].depType;
						dutyName = tempData[0].dutys ? tempData[0].dutys[0].dutyName : '';
						dutyId = tempData[0].dutys ? tempData[0].dutys[0].dutyId : '';
					}
					console.log(orgCode, JSON.stringify(orgCode), 'JSON.stringify(orgCode)');
					uni.setStorageSync('orgName', JSON.stringify(orgName));
					uni.setStorageSync('orgId', JSON.stringify(orgId));
					uni.setStorageSync('orgCode', JSON.stringify(orgCode));
					uni.setStorageSync('depTypeCode', JSON.stringify(depTypeCode));
					uni.setStorageSync('dutyName', JSON.stringify(dutyName));
					uni.setStorageSync('dutyId', JSON.stringify(dutyId));
					uni.setStorageSync('dutyData', JSON.stringify(tempData));
				}
			}
		},
		setHeaderCookie(userData) {
			let header = {
				Authorization: 'Bearer ' + JSON.parse(uni.getStorageSync('token')),
				appCode: userData.app_code,
				orgCode: encodeURIComponent(userData.user.orgCode),
				userId: userData.user.userId,
				userName: encodeURIComponent(userData.user.userName),
				userCode: encodeURIComponent(userData.user.userCode),
				roleCodes: encodeURIComponent(uni.getStorageSync('roleCodes')),
				dilCompanyList: encodeURIComponent(JSON.stringify(userData.user.dilCompanyList)),
				rootCompanyMap: encodeURIComponent(JSON.stringify(userData.user.rootCompanyMap))
			};
			uni.setStorageSync('header', JSON.stringify(header));
		},
		// 绑定账号与Cid
		async bindCid(userId) {
			let cid = uni.getStorageSync('getui_cid');
			const res = await this.$myRequest({
				url: '/api/v1/bp/insertAppCid',
				data: {
					userCode: this.userName,
					cid: cid,
					insertUsername: userId
				}
			}).catch((err) => {
				console.error(err);
			});
		},
		async onclick() {
			//保存最初的账号
			let name = this.userName;
			let _this = this;
			this.passwordSha1 = sha1(this.password);
			uni.setStorage({
				key: 'userName',
				data: this.userName
			});
			uni.setStorage({
				key: 'passWord',
				data: this.password
			});
			let loginFormData = {};
			let cid = uni.getStorageSync('getui_cid');
			loginFormData = {
				loginName: this.userName,
				password: this.passwordSha1,
				app_code: 'App',
				cid: cid
			};
			const res = await this.$myRequest({
				name: 'loginRequest',
				url: '/api/v1/bp/bpLogin',
				data: loginFormData,
				mask: true,
				method: 'POST',
				header: {
					'Content-Type': 'application/x-www-form-urlencoded'
				},
				dataType: 'json'
			}).catch((err) => {
				uni.showToast({
					title: err,
					icon: 'none',
					duration: 2000
				});
			});
			if (res.data.code == '0') {
				let userData = res.data.data;
				try {
					uni.setStorageSync('companyId', userData.user.companyId);
					uni.setStorageSync('token', JSON.stringify(userData.accessToken));
					uni.setStorageSync('appId', userData.appId);
					uni.setStorageSync('userInfo', JSON.stringify(userData.user));
					uni.setStorageSync('userId', userData.user.userId);
					uni.setStorageSync('userName', this.userName);
					uni.setStorageSync('capacityId', userData.capacityId);
					uni.setStorageSync('capacityNumber', userData.capacityNumber);
					uni.setStorageSync('driverId', userData.driverId);
					uni.setStorageSync('driverName', userData.driverName);
					uni.setStorageSync('personnelId', userData.personnelId);
					uni.setStorageSync('personnelName', userData.personnelName);
					uni.setStorageSync('personnelPost', userData.personnelPost);
					uni.setStorageSync('personnelTeam', userData.personnelTeam);
					let roleArr = [];
					userData.user.sysRoles.forEach((e) => {
						roleArr.push(e.roleCode);
					});
					uni.setStorageSync('roleCodes', JSON.stringify(roleArr));
					if (userData.user.dilCompanyList) {
						uni.setStorageSync('dilCompanyList', JSON.stringify(userData.user.dilCompanyList));
					}
					if (userData.user.rootCompanyMap) {
						uni.setStorageSync('rootCompanyMap', JSON.stringify(userData.user.rootCompanyMap));
					}
					this.setHeaderCookie(userData);
					this.getDytys(userData.user);
					this.sendMessage();
					this.bindCid(userData.user.userId);
				} catch (e) {
					//TODO handle the exception
					uni.showToast({
						icon: 'none',
						title: e.message
					});
				}
			} else {
				console.log(res, 'res');
				uni.showToast({
					title: res.data.message,
					icon: 'none'
				});
			}
		},
		//TpvwClq7
		//获取当前最新的版本号对比结果  0为版本相同1为不相同
		async getVersion() {
			const res = await this.$myRequest({
				url: '/api/v1/uc/getAppVersion',
				method: 'POST'
			});
			if (res.statusCode == '200') {
				console.log(res.data.data, 'data');
				if (plus.runtime.version != res.data.data) {
					this.getupdate();
				}
			}
		},
		// 热更新
		getupdate() {
			uni.showLoading({
				title: '更新中,请耐心等待',
				mask: true
			});
			//对比版本号
			uni.downloadFile({
				url: 'http://wl.antaigroup.com:8795/data/file/物流平台.apk',
				success: (downloadResult) => {
					uni.hideLoading();
					if (downloadResult.statusCode === 200) {
						plus.runtime.install(
							downloadResult.tempFilePath,
							{
								force: false
							},
							function () {
								// 记录热更新文件的版本号
								uni.setStorageSync('version2', data.hotupdate_version);
								uni.showModal({
									title: 'app更新已就绪是否立即更新',
									content: '',
									success: (showResult) => {
										if (showResult.confirm) {
											plus.runtime.restart();
										}
									}
								});
							},
							function (e) {}
						);
					}
				},
				fail: (downloadResult) => {}
			});
		},
		register() {
			this.$refs.popup.open();
			this.formShow = true;
		},
		canceAdd() {
			this.formShow = false;
			this.$refs.popup.close();
		},
		confirmAdd() {
			this.$refs['form_rgt'].validateForm((data) => {
				if (data.flag) {
					this.Tool.uploadFile(this.form_rgt, ['driverLisencePhoto'], (response) => {
						this.addDriverInfo(response);
					});
				} else {
					console.log('res: ');
				}
			});
		},
		async addDriverInfo(data) {
			data.roleId = '';
			data.ssoId = '';
			data.roleIds = [];
			data.personnelPhone = data.personnelJobNumber;
			data.personnelPost = '司机';
			let url = '/api/v1/rms/insertPersonnel';
			if (data.updateFlag == 'update') {
				url = '/api/v1/rms/updatePersonnel';
			}
			const res = await this.$myRequest({
				url: url,
				data: data
			}).catch((err) => {
				uni.showToast({
					duration: 2000,
					title: err,
					icon: 'error'
				});
			});
			if (res.data.status == 'succeed') {
				uni.showToast({
					icon: 'success',
					title: '注册成功！请登录！',
					duration: 2000
				});
				this.canceAdd();
				this.form = {};
			} else {
				uni.showToast({
					icon: 'none',
					title: res.data.message,
					duration: 2000
				});
			}
		}
	}
};
</script>

<style lang="scss" scoped>
.status_bar {
	height: var(--status-bar-height);
	width: 100%;
}
.loginContent {
	width: 100vw;
	height: 100vh;
	background: url('../../static/login/bg.png'), no-repeat;
	background-size: cover;
	display: flex;
	flex-direction: column;
	justify-content: center;
	align-items: center;
	.loginTop {
		margin-bottom: 100rpx;
		.loginLog {
			width: 200upx;
			height: 200upx;
			.img {
				width: 200rpx;
				height: 200rpx;
			}
		}
	}
	.loginMain {
		margin-top: 10rpx;
		width: 80vw;
		.uni-section {
			border-radius: 16rpx;
			background-color: #00aded;
			opacity: 0.9;
			padding: 0;
			.uni-easyinput {
				margin-left: 20rpx;
				width: 75vw;
				// padding: 0;
				height: 80rpx;
				margin-top: 20rpx;
			}
			.forgetPwd {
				margin-top: 10rpx;
				margin-right: 20rpx;
				margin-bottom: 10rpx;
				text-align: right;
				font-size: 26rpx;
				font-weight: 300;
			}
		}
	}
	.loginBtn {
		margin-top: 30rpx;
		width: 80vw;
		.btn {
			background-color: #00aded;
			color: #ffffff;
			border-radius: 80rpx;
		}
	}
	.loginFloot {
		color: #ffffff;
		position: fixed;
		bottom: 60rpx;
		text-align: center;
		font-size: 27rpx;
	}
	.updateBtn {
		color: #ffffff;
		position: fixed;
		bottom: 10rpx;
		font-size: 27rpx;
		text-decoration-line: underline;
	}
}
</style>
